import time
from PIL import Image
from cnocr import CnOcr
import pyautogui

class MLabel:
    def __init__(self,name:str,region:tuple[int],mtext:str):
        self.name = name
        self.region = region
        self.mtext = mtext
        if(mtext.find('img:') == 0):
            self.img = Image.open(mtext[4:len(mtext)])
        else:
            self.img = None
        if(region[2] == 0 or region[3] == 0):
            self.region = (self.region[0],self.region[1],self.img.width,self.img.height)

class MWindow:
    def __init__(self,name:str,region:tuple[int]):
        self.name = name
        self.labels = []
        self.region = region
    def Add(self,label:MLabel):
        self.labels.append(label)
    def __GetLabel(self,name:str='',index:int=-1)->MLabel:
        if index == -1 and name == '':
            return None
        label:MLabel = None
        if index != -1:
            label = self.labels[index]
        else:
            for la in self.labels:
                if la.name == name:
                    label = la
        return label
    def GetLabelImg(self,name:str='',index:int=-1)->Image:
        if len(self.labels) <= 0:
            return None
        label = self.__GetLabel(name=name,index=index)
        region = (label.region[0]+self.region[0],
                label.region[1]+self.region[1],
                label.region[2],
                label.region[3])
        img = pyautogui.screenshot(region=region)
        return img
    def GetLabelText(self,name:str='',index:int=-1,multiline:bool=False)->str:
        if len(self.labels) <= 0:
            return None
        label = self.__GetLabel(name=name,index=index)
        ocr = CnOcr()
        region = (label.region[0]+self.region[0],
                label.region[1]+self.region[1],
                label.region[2],
                label.region[3])
        img = pyautogui.screenshot(region=region)
        # img.save("capture/test.png")
        out = ocr.ocr(img)
        if len(out) == 0:
            print(f'GetLabelText: name={name},index={index},ocr failed')
            return None
        if multiline:
            text = ''
            for v in out:
                text += v['text']
        else:
            text = out[0]['text']
        print(f'GetLabelText: name={name},index={index},text={text}')
        return text
    def GetLabelMultiText(self,name:str='',index:int=-1)->list[str]:
        if len(self.labels) <= 0:
            return None
        label = self.__GetLabel(name=name,index=index)
        ocr = CnOcr()
        region = (label.region[0]+self.region[0],
                label.region[1]+self.region[1],
                label.region[2],
                label.region[3])
        img = pyautogui.screenshot(region=region)
        # img.save("capture/test.png")
        out = ocr.ocr(img)
        if len(out) == 0:
            print(f'GetLabelMultiText: name={name},index={index},ocr failed')
            return None
        rtn = []
        for v in out:
            rtn.append(v['text'])
        print(f'GetLabelMultiText: name={name},index={index},text={rtn}')
        return rtn
    def ExistLabel(self,name:str='',index:int=-1,confidence:float=0.7):
        if len(self.labels) <= 0:
            return None
        label = self.__GetLabel(name=name,index=index)
        if label == None:
            return None
        poss = 1
        if label.img == None:
            if label.mtext == '':
                return None
            ocr = CnOcr()
            region = (label.region[0]+self.region[0],
                    label.region[1]+self.region[1],
                    label.region[2],
                    label.region[3])
            img = pyautogui.screenshot(region=region)
            out = ocr.ocr(img)
            if len(out) == 0:
                return None
            text = out[0]['text']
            if text != label.mtext:
                return None
        else:
            try:
                rect = (label.region[0]+self.region[0],
                        label.region[1]+self.region[1],
                        label.region[2],
                        label.region[3])
                poss = pyautogui.locateOnScreen(image=label.img,region=rect,confidence=confidence)
                if(len(poss) <= 0):
                    return None
                #poss = (box.left,box.top,box.width,box.height)
            except Exception as e:
                print(f'locateOnScreen: failed,winname={self.name},name={label.name},region={rect},e={e}')
                # if self.name == '获得奖励':
                #     r = (rect[0],rect[1],100,100)
                #     img = pyautogui.screenshot(region=r)
                #     img.save("capture/test2.png")
                return None                
        print(f'ExistLabel: true,name={label.name}')
        return poss
    def ClickLabel(self,name:str='',index:int=-1):
        if len(self.labels) <= 0:
            raise Exception("labels个数为0!")
        label = self.__GetLabel(name=name,index=index)
        if label == None:
            raise Exception("label为空!")
        x = label.region[0]+self.region[0]+label.region[2]/2
        y = label.region[1]+self.region[1]+label.region[3]/2
        print(f'click winname={self.name},name={label.name}, {x},{y}')
        pyautogui.click(x,y)
    def ClickYAxisLabel(self,name:str='',index:int=-1,poss=None):
        if len(self.labels) <= 0:
            raise Exception("labels个数为0!")
        label = self.__GetLabel(name=name,index=index)
        x=y=0
        if label.img == None:
            raise Exception("label识字类型待做!")
        else:
            x = label.region[0]+self.region[0]+label.region[2]/2
            y = poss.top+poss.height/2
        print(f'click {x},{y}')
        pyautogui.click(x,y)
        return True

class MWindowSet:
    def __init__(self,region:tuple):
        self.mwindows = []
        self.region = region
    def Load(self,filename):
        a = '国王'
        with open(filename,encoding='utf-8') as file:
            mwin = None
            for line in file:
                line = line.rstrip('\n')
                if line[0] == '#':
                    if mwin != None:
                        self.Add(mwin)
                    mwin = MWindow(line[1:len(line)],self.region)
                else:
                    ss = line.split('|')
                    name = ss[0]
                    s_region = ss[1].split(',')
                    imgname = ss[2]
                    label = MLabel(name,(int(s_region[0]),int(s_region[1]),int(s_region[2]),int(s_region[3])),imgname)
                    mwin.Add(label)
            if mwin != None:
                self.Add(mwin)
    def Add(self,window:MWindow):
        self.mwindows.append(window)
    def CheckWindow(self)->MWindow:
        for window in self.mwindows:
            if window.ExistLabel(index=0):
                print(f"checkwindow: {window.name}")
                return window
        return None
            
    

